// npm i cordova-plugin-chrome-apps-sockets-udp

var serialudp = function (callback, _port) {
    // function buf2hex(buffer, space) { // buffer is an ArrayBuffer
    //     return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join(space);
    // }

    // function hex2buf(key, space) {
    //     key = '0x' + (key).replace(new RegExp(space, 'g'), ',0x');
    //     return new Uint8Array(key.split(",")).buffer;
    // }

    var socketId;
    // Handle the "onReceive" event.
    var onReceive = function (info) {
        // console.log('收到：' + buf2hex(info.data, ' '));
        // $('#msg').prepend(btntitle + ' | IP:' + info.remoteAddress + ' Port:' + info.remotePort + '<br>' + info.data + '<br>')
        callback && callback(info.data,info);
    };

    // Create the Socket
    chrome.sockets.udp.create({}, function (socketInfo) {
        socketId = socketInfo.socketId;
        // Setup event handler and bind socket.
        chrome.sockets.udp.onReceive.addListener(onReceive);
        chrome.sockets.udp.bind(socketId, "0.0.0.0", _port||10101, function (result) {
            if (result < 0) {
                console.log("Error binding socket..................");
                return;
            }
        });
    });
    return {
        send: function (str, ip, port, unit) {
            var data=str;
            if(unit=="hex"){
                data = str.replace(/-+|\s+/g, "");
            }
            chrome.sockets.udp.send(socketId, Buffer.from(data, unit||"ASCII"),
                ip, port, function (sendInfo) {
                    console.log("sent " + sendInfo.bytesSent);
                });
        }
    }
}
